package com.xingchen.feima.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xingchen.feima.system.entity.Menu;
import com.xingchen.feima.system.entity.vo.RouteVo;
import com.xingchen.feima.system.mapper.MenuMapper;
import com.xingchen.feima.system.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xingchen.feima.system.utils.MenuHelper;
import com.xingchen.feima.system.utils.RouterHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author yangxc
 * @since 2024-07-27
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<RouteVo> getRouteVoList(Long userId) {
        // 约定id为1的账号为超级管理员
        // 获取已分配菜单列表
        List<Menu> alreadyAssignedMenuList = new ArrayList<>();
        if (userId == 1) {
            alreadyAssignedMenuList = menuMapper.selectList(new QueryWrapper<Menu>().eq("status", 1).orderByAsc("sort_value"));
        } else {
            alreadyAssignedMenuList = menuMapper.findMenuListByUserId(userId);
        }
        // 构建菜单树形数据
        List<Menu> menuTreeList = MenuHelper.buildTree(alreadyAssignedMenuList);

        // 构建路由列表
        List<RouteVo> routeVoList = RouterHelper.buildRouters(menuTreeList);
        return routeVoList;
    }

    @Override
    public List<String> findUserPermsList(Long userId) {
        //超级管理员admin账号id为：1
        List<Menu> sysMenuList = new ArrayList<>();
        if (userId.longValue() == 1) {
            sysMenuList = menuMapper.selectList(new QueryWrapper<Menu>().eq("status", 1));
        } else {
            sysMenuList = menuMapper.findMenuListByUserId(userId);
        }
        //创建返回的集合
        List<String> permissionList = new ArrayList<>();
        for (Menu sysMenu : sysMenuList) {
            if(sysMenu.getType() == 2){
                permissionList.add(sysMenu.getPerms());
            }
        }
        return permissionList;
    }
}
